import { NextRequest, NextResponse } from 'next/server';
import { getDb } from '@/lib/db';
import { getCurrentUser, isAdmin } from '@/middleware/auth';
import { AuthService } from '@/lib/auth';
import { User } from '@/lib/db/auth-schema';

/**
 * 获取用户详情
 * GET /api/admin/users/[id]
 */
export async function GET(
  request: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    // 验证管理员权限
    let currentUser = getCurrentUser(request);
    
    // 如果getCurrentUser没有返回用户信息，尝试直接验证token
    if (!currentUser) {
      const authHeader = request.headers.get('authorization');
      const cookieHeader = request.headers.get('cookie');
      let token: string | null = null;
      
      if (authHeader && authHeader.startsWith('Bearer ')) {
        token = authHeader.substring(7);
      } else if (cookieHeader) {
        const cookies = cookieHeader.split(';').reduce((acc: any, cookie) => {
          const [key, value] = cookie.trim().split('=');
          acc[key] = value;
          return acc;
        }, {});
        token = cookies['auth-token'] || null;
      }
      
      if (token) {
        const tokenResult = await AuthService.verifyToken(token);
        if (tokenResult.valid && tokenResult.payload) {
          currentUser = tokenResult.payload;
        }
      }
    }
    
    if (!currentUser || !isAdmin(currentUser)) {
      return NextResponse.json(
        { success: false, error: '权限不足' },
        { status: 403 }
      );
    }

    const { id } = params;
    const db = await getDb();

    // 获取用户基本信息
    const userResult = await db.findOne<User>('users', { id });
    const user = userResult.success ? userResult.data : null;

    if (!user) {
      return NextResponse.json(
        { success: false, error: '用户不存在' },
        { status: 404 }
      );
    }

    // 获取用户角色信息（简化版本，基于用户的role字段）
    const userRoles = user ? [{ name: user.role, description: `${user.role} role` }] : [];

    // 获取用户权限信息（简化版本）
    const userPermissions: any[] = [];

    // 获取登录历史（简化版本）
    const loginHistory: any[] = [];

    return NextResponse.json({
      success: true,
      data: {
        user,
        roles: userRoles,
        permissions: userPermissions,
        loginHistory
      }
    });

  } catch (error) {
    console.error('获取用户详情失败:', error);
    return NextResponse.json(
      { success: false, error: '获取用户详情失败' },
      { status: 500 }
    );
  }
}

/**
 * 更新用户信息
 * PUT /api/admin/users/[id]
 */
export async function PUT(
  request: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    // 验证管理员权限
    let currentUser = getCurrentUser(request);
    
    // 如果getCurrentUser没有返回用户信息，尝试直接验证token
    if (!currentUser) {
      const authHeader = request.headers.get('authorization');
      const cookieHeader = request.headers.get('cookie');
      let token: string | null = null;
      
      if (authHeader && authHeader.startsWith('Bearer ')) {
        token = authHeader.substring(7);
      } else if (cookieHeader) {
        const cookies = cookieHeader.split(';').reduce((acc: any, cookie) => {
          const [key, value] = cookie.trim().split('=');
          acc[key] = value;
          return acc;
        }, {});
        token = cookies['auth-token'] || null;
      }
      
      if (token) {
        const tokenResult = await AuthService.verifyToken(token);
        if (tokenResult.valid && tokenResult.payload) {
          currentUser = tokenResult.payload;
        }
      }
    }
    
    if (!currentUser || !isAdmin(currentUser)) {
      return NextResponse.json(
        { success: false, error: '权限不足' },
        { status: 403 }
      );
    }

    const { id } = params;
    const body = await request.json();
    const { username, email, display_name, role, status, password } = body;

    const db = await getDb();

    // 检查用户是否存在
    const userResult = await db.findOne<User>('users', { id });
    const existingUser = userResult.success ? userResult.data : null;

    if (!existingUser) {
      return NextResponse.json(
        { success: false, error: '用户不存在' },
        { status: 404 }
      );
    }

    // 检查用户名和邮箱是否被其他用户使用
    if (username && username !== existingUser.username) {
      const existingResult = await db.findOne<User>('users', { username });
      if (existingResult.success && existingResult.data && existingResult.data.id !== id) {
        return NextResponse.json(
          { success: false, error: '用户名已被使用' },
          { status: 409 }
        );
      }
    }

    if (email && email !== existingUser.email) {
      const existingResult = await db.findOne<User>('users', { email });
      if (existingResult.success && existingResult.data && existingResult.data.id !== id) {
        return NextResponse.json(
          { success: false, error: '邮箱已被使用' },
          { status: 409 }
        );
      }
    }

    // 验证角色
    if (role) {
      const validRoles = ['super_admin', 'admin', 'editor', 'user', 'guest'];
      if (!validRoles.includes(role)) {
        return NextResponse.json(
          { success: false, error: '无效的角色' },
          { status: 400 }
        );
      }
    }

    // 构建更新数据
    const updateData: Partial<User> = {
      updated_at: new Date().toISOString()
    };
    
    if (username) updateData.username = username;
    if (email) updateData.email = email;
    if (display_name !== undefined) updateData.display_name = display_name;
    if (role) updateData.role = role as User['role'];
    if (status) updateData.status = status as User['status'];
    
    if (password) {
      const bcrypt = require('bcryptjs');
      const hashedPassword = await bcrypt.hash(password, 12);
      updateData.password_hash = hashedPassword;
    }

    if (Object.keys(updateData).length === 1) { // 只有updated_at
      return NextResponse.json(
        { success: false, error: '没有提供要更新的字段' },
        { status: 400 }
      );
    }

    // 执行更新
    const updateResult = await db.update<User>('users', { id }, updateData);

    if (!updateResult.success) {
      return NextResponse.json(
        { success: false, error: '更新用户信息失败' },
        { status: 500 }
      );
    }

    // 获取更新后的用户信息
    const updatedUserResult = await db.findOne<User>('users', { id });
    const updatedUser = updatedUserResult.success ? updatedUserResult.data : null;

    return NextResponse.json({
      success: true,
      data: updatedUser,
      message: '用户信息更新成功'
    });

  } catch (error) {
    console.error('更新用户信息失败:', error);
    return NextResponse.json(
      { success: false, error: '更新用户信息失败' },
      { status: 500 }
    );
  }
}

/**
 * 删除用户
 * DELETE /api/admin/users/[id]
 */
export async function DELETE(
  request: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    // 验证管理员权限
    let currentUser = getCurrentUser(request);
    
    // 如果getCurrentUser没有返回用户信息，尝试直接验证token
    if (!currentUser) {
      const authHeader = request.headers.get('authorization');
      const cookieHeader = request.headers.get('cookie');
      let token: string | null = null;
      
      if (authHeader && authHeader.startsWith('Bearer ')) {
        token = authHeader.substring(7);
      } else if (cookieHeader) {
        const cookies = cookieHeader.split(';').reduce((acc: any, cookie) => {
          const [key, value] = cookie.trim().split('=');
          acc[key] = value;
          return acc;
        }, {});
        token = cookies['auth-token'] || null;
      }
      
      if (token) {
        const tokenResult = await AuthService.verifyToken(token);
        if (tokenResult.valid && tokenResult.payload) {
          currentUser = tokenResult.payload;
        }
      }
    }
    
    if (!currentUser || !isAdmin(currentUser)) {
      return NextResponse.json(
        { success: false, error: '权限不足' },
        { status: 403 }
      );
    }

    const { id } = params;
    const db = await getDb();

    // 检查用户是否存在
    const userResult = await db.findOne<User>('users', { id });
    const user = userResult.success ? userResult.data : null;

    if (!user) {
      return NextResponse.json(
        { success: false, error: '用户不存在' },
        { status: 404 }
      );
    }

    // 防止用户删除自己
    if (user.id === currentUser.userId) {
      return NextResponse.json(
        { success: false, error: '不能删除自己的账户' },
        { status: 400 }
      );
    }

    // 防止删除超级管理员（如果当前用户不是超级管理员）
    if (user.role === 'super_admin' && currentUser.role !== 'super_admin') {
      return NextResponse.json(
        { success: false, error: '权限不足，无法删除超级管理员' },
        { status: 403 }
      );
    }

    // 删除用户
    const deleteResult = await db.delete('users', { id });
    
    if (!deleteResult.success) {
      return NextResponse.json(
        { success: false, error: '删除用户失败' },
        { status: 500 }
      );
    }

    return NextResponse.json({
      success: true,
      message: `用户 ${user.username} 删除成功`
    });

  } catch (error) {
    console.error('删除用户失败:', error);
    return NextResponse.json(
      { success: false, error: '删除用户失败' },
      { status: 500 }
    );
  }
}